package com.jdy.haoduoai.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.text.TextWatcher;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jdy.haoduoai.Constant;
import com.jdy.haoduoai.EventWatcher;
import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.intface.IAsyncTask;
import com.jdy.haoduoai.model.LeMachine;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.parse.JsonSerializer;
import com.jdy.haoduoai.socket.SocketInputThread;
import com.jdy.haoduoai.socket.SocketThreadManager;
import com.jdy.haoduoai.util.CustomAsyncTask;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.LeConfig;
import com.jdy.haoduoai.util.PathUtil;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.jdy.haoduoai.view.RippleView;
import com.jdy.haoduoai.view.RippleView.OnRippleCompleteListener;
import com.umeng.analytics.MobclickAgent;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.StringTokenizer;
import java.util.Timer;
import java.util.TimerTask;

//import com.jdy.haoduoai.R;

/**
 * 登录
 * 
 * @author Administrator
 * 
 */
@SuppressLint("HandlerLeak")
public class LoginActivity extends BaseActivity implements OnClickListener {
  @InjectView(id = R.id.find_password, click = true)
  private TextView find_pass;
  @InjectView(id = R.id.input_tel)
  private org.droidparts.widget.ClearableEditText tel;
  @InjectView(id = R.id.input_password)
  private org.droidparts.widget.ClearableEditText password;
  @InjectView(id = R.id.loginRippleView)
  private RippleView mLoginRippleView;
  @InjectView(id = R.id.tv_register, click = true)
  private TextView tv_register;
  @InjectView(id = R.id.tel)
  private RelativeLayout mTelephoneNumberLayout;
  @InjectView(id = R.id.password)
  private RelativeLayout mPasswordLayout;
  @InjectView(id = R.id.login, click = true)
  private Button login;

  @SuppressWarnings("unused")
  private void notification() {
    String html = "我是乐小宝<img src='emoji'/>";
    CharSequence charSequence = Html.fromHtml(html, new ImageGetter() {

      @Override
      public Drawable getDrawable(String source) {
        Drawable drawable = getResources().getDrawable(
            Tools.getResourceId(source));
        {
          drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
              drawable.getIntrinsicHeight());
        }
        return drawable;
      }
    }, null);
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login_layout);

    setTitle("登录");
    mBackImageButton.setVisibility(View.INVISIBLE);
    mUprightButton.setVisibility(View.GONE);
    initView();

    SharedPreferences prefs = this.getSharedPreferences(Constant.USER_INFO,
        Context.MODE_PRIVATE);
    String telno = prefs.getString(Constant.TEL, "");
    String pwd = prefs.getString(Constant.PWD, "");
    if (Tools.isEmpty(telno) || Tools.isEmpty(pwd)) {
      showKeyboard();
    } else {
      tel.setText(telno);
      password.setText(pwd);
    }
  }

  private void showKeyboard() {
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
      @Override
      public void run() {
        InputMethodManager inputManager = (InputMethodManager) tel.getContext()
            .getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(tel, 0);
      }
    }, 200);
  }

  private void updateBtnStatus() {
    if (Tools.isEmpty(tel.getText().toString().replaceAll(" ", ""))
        || Tools.isEmpty(password.getText().toString().replaceAll(" ", ""))
        || password.getText().toString().replaceAll(" ", "").length() < 6) {
      login.setEnabled(false);
      mLoginRippleView.setEnabled(false);
    } else {
      login.setEnabled(true);
      mLoginRippleView.setEnabled(true);
    }
  }

  private void initView() {
    find_pass.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
    find_pass.getPaint().setAntiAlias(true);
    password
        .setTransformationMethod(PasswordTransformationMethod.getInstance());

    mLoginRippleView
        .setOnRippleCompleteListener(new OnRippleCompleteListener() {
          @Override
          public void onComplete(RippleView rippleView) {
            login();
          }
        });

    updateBtnStatus();

    tel.addTextChangedListener(new TextWatcher() {
      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count) {
      }

      @Override
      public void beforeTextChanged(CharSequence s, int start, int count,
          int after) {
      }

      @Override
      public void afterTextChanged(Editable s) {
        updateBtnStatus();
      }
    });

    password.addTextChangedListener(new TextWatcher() {
      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count) {

      }

      @Override
      public void beforeTextChanged(CharSequence s, int start, int count,
          int after) {

      }

      @Override
      public void afterTextChanged(Editable s) {
        updateBtnStatus();
      }
    });
  }

  private void storeUserInfo() {
    SharedPreferences prefs = this.getSharedPreferences(Constant.USER_INFO,
        Context.MODE_PRIVATE);
    prefs.edit().putString(Constant.TEL, tel.getText().toString()).apply();
    prefs.edit().putString(Constant.PWD, password.getText().toString()).apply();
  }

  private void doPageRoute() {
    if (LeConfig.isLogin) {
      if (LeConfig.isDeviceBinded) {
        if (LeConfig.isInfoFilled) {

          if (LeConfig.isDeviceActivated) {

          } else {

          }

          Intent intent = new Intent(this, MainActivity.class);
          intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
          startActivity(intent);

          finish();

        } else {
          Intent t = new Intent(LoginActivity.this, FillInfoPopupActivity.class);
          t.putExtra("fromPage", "LoginActivity");
          startActivity(t);
          finish();
        }
      } else {
        Intent t = new Intent(LoginActivity.this, ConnectWifiActivity.class);
        startActivity(t);
        finish();
      }
    } else {
    }
  }

  private void login() {

    CustomAsyncTask async = new CustomAsyncTask(LoginActivity.this,
        new IAsyncTask() {
          @Override
          public void onRecieveData(Activity activity, ResponseResult result) {

            MobclickAgent.onEvent(LoginActivity.this,
                EventWatcher.EVENT_XIAOXIAOBAN_LOGIN);

            if (result.isSuccess() && Tools.isNotNullStr(result.data)) {

              LeUser lu = JsonSerializer.getInstance().deserialize(result.data,
                  LeUser.class);

              LeConfig.isLogin = true;
              SocketInputThread.kickOffline = false;
              storeUserInfo();

              LeMachine leBaby = null;
              if (lu != null) {
                leBaby = lu.machine;
              }

              if (leBaby != null && !leBaby.toString().equals("null")
                  && Tools.isNotEmpty(leBaby.id)) {
                LeConfig.isDeviceBinded = true;
                LeConfig.MAC_ID = leBaby.id;
                LeConfig.babyname = leBaby.name;

                getBabyAvatar(leBaby.avatar);
                LeXiaoXiaoBanApp.getInstance().setBaby(leBaby);
                // checkDeviceVersion(leBaby.version);

                String url = leBaby.ip;
                if (Tools.isNotNullStr(url)) {
                  StringTokenizer tokens = new StringTokenizer(url, ":");
                  LeConfig.g_ServerIP = tokens.nextToken();
                  Log.e("LoginActivity", "============" + LeConfig.g_ServerIP);
                  LeConfig.FILE_PORT = Integer.parseInt(tokens.nextToken());
                  Log.e("LoginActivity", "============" + LeConfig.FILE_PORT);

                  SocketThreadManager.releaseInstance();
                   SocketThreadManager.getInstance().disconnectOldConnectNew();
//                   stm.setDeviceStateListener(MainActivity.this);
//                   stm.requestDeviceDetails();
//                   startService(new Intent(LoginActivity.this,
//                   LeSocketManagerService.class));

                }

                if (lu != null && Tools.isNotEmpty(leBaby.name)
                    && Tools.isNotEmpty(lu.nickname)) {
                  LeConfig.isInfoFilled = true;

                  if (Tools.isNotEmpty(leBaby.activate)
                      && !leBaby.activate.toString().equals("null")) {
                    LeConfig.isDeviceActivated = !leBaby.activate.is_expired;
                    LeConfig.expiredAt = leBaby.activate.expired_at;
                  }
                } else {
                  LeConfig.isInfoFilled = false;
                }

              } else {
                LeConfig.isDeviceBinded = false;
              }

              if (lu != null) {
                LeConfig.PHONE_NUM = lu.id;
                LeConfig.nickname = lu.nickname;
              }

              LeXiaoXiaoBanApp.getInstance().setUser(lu);
              Tools.saveLeUser(lu);
              Tools.saveLeBaby(leBaby);

              Intent intent = new Intent("com.jdy.haoduoai.activity.login");
              sendBroadcast(intent);

              if (lu != null && Tools.isNotEmpty(lu.avatar)) {
                getHeadImage(lu.avatar);
              } else {
                dismissLoading();
                toastShow("登录成功!");

                MobclickAgent.onProfileSignIn(LeConfig.PHONE_NUM);

                doPageRoute();
              }

            } else { // failed
              dismissLoading();

              Animation shake = AnimationUtils.loadAnimation(
                  LoginActivity.this, R.anim.anim_shake);
              mTelephoneNumberLayout.startAnimation(shake);
              mPasswordLayout.startAnimation(shake);
              toastShow(result.data);
            }
          }

          @Override
          public ResponseResult doInbackground(Activity activity) {
            HashMap<String, Object> param_ = new HashMap<String, Object>();
            param_.put(HttpUtils.TAG_MOBILE_I, tel.getText().toString());
            param_.put(HttpUtils.TAG_PWD_I, password.getText().toString());
            param_.put(HttpUtils.TAG_PLATFORM_I, "android");
            param_.put(HttpUtils.TAG_TOKEN_I, "test");
            param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

            return HttpUtils.startRequestEncrypt(HttpUtils.API_URL
                + HttpUtils.LOGIN_METHOD_POST, param_,
                HttpUtils.TAG_POST_REQUEST);
          }
        });
    async.execute();

    showloading(async, "正在登录...", new CancelLoadingDialogListener() {

      @Override
      public void onCancel() {

      }
    });
  }

  @Override
  protected void onNewIntent(Intent intent) {
    setIntent(intent);

    if (tel != null) {
      tel.setText("");
    }

    if (password != null) {
      password.setText("");
    }

    super.onNewIntent(intent);
  }

  private void getHeadImage(String remoteHeadImageFilePath) {

    if (Tools.isNullStr(remoteHeadImageFilePath)) {
      return;
    }

    new AsyncTask<String, Void, Bitmap>() {
      @Override
      protected void onPostExecute(Bitmap result) {
        if (result != null) {
          String path = PathUtil.getElderAvatarPath(getApplicationContext());
          FileOutputStream out = null;
          try {
            File parentAvatarFile = new File(path);
            if (!parentAvatarFile.exists()) {
              parentAvatarFile.createNewFile();
            }
            out = new FileOutputStream(parentAvatarFile);
            result.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is
                                                                  // your
                                                                  // Bitmap
                                                                  // instance
            // PNG is a lossless format, the compression factor (100) is
            // ignored
            SharedPreferences prefs = getSharedPreferences(Constant.USER_INFO,
                Context.MODE_PRIVATE);
            Uri parentAvatarUri = Uri.fromFile(parentAvatarFile);
            prefs.edit()
                .putString(Constant.PARENT_AVATAR, parentAvatarUri.toString())
                .apply();
          } catch (Exception e) {
            e.printStackTrace();
          } finally {
            try {
              if (out != null) {
                out.close();
              }
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
        }

        dismissLoading();
        toastShow("登录成功!");

        MobclickAgent.onProfileSignIn(LeConfig.PHONE_NUM);

        doPageRoute();
      }

      @Override
      protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];

        Bitmap resultImage = null;

        URL url;
        try {
          url = new URL(urldisplay);

          HttpURLConnection urlConnection = (HttpURLConnection) url
              .openConnection();

          urlConnection.setRequestMethod("GET");
          // urlConnection.setDoOutput(true);
          urlConnection.connect();

          InputStream in = urlConnection.getInputStream();
          resultImage = BitmapFactory.decodeStream(in);

        } catch (MalformedURLException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
        return resultImage;
      }
    }.execute(remoteHeadImageFilePath);

  }

  // protected void getBabyInfo(final int babyId, final LeUser lu) {
  // new CustomAsyncTask(this, new IAsyncTask() {
  //
  // @Override
  // public void onRecieveData(Activity activity, final ResponseResult result) {
  //
  // if (result.isSuccess() && Tools.isNotNullStr(result.data)) {
  //
  // LeMachine lb = JsonSerializer.getInstance().deserialize(result.data,
  // LeMachine.class);
  //
  // getBabyAvatar(lb.avatar);
  // LeXiaoXiaoBanApp.getInstance().setBaby(lb);
  // // checkDeviceVersion(lb.version);
  // } else {
  // toastShow(result.data);
  // }
  //
  // }
  //
  // @Override
  // public ResponseResult doInbackground(Activity activity) {
  //
  // HashMap<String, Object> param_ = new HashMap<String, Object>();
  // param_.put(HttpUtils.TAG_SNO_I, lu.sno);
  // param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
  //
  // return HttpUtils.startRequest(HttpUtils.API_URL
  // + HttpUtils.GET_BABY_METHOD_GET + babyId, param_,
  // HttpUtils.TAG_GET_REQUEST);
  // }
  // }).execute();
  // }

  /**
   * 设备升级提示
   * 
   */
  // public void checkDeviceVersion(String version) {
  // if (Tools.isNotEmpty(version)) {
  // try {
  // int currentDeviceVersion = Integer.valueOf(version.replaceAll("\\D+",
  // ""));
  // LeConfig.CURRENT_DEVICE_VERSION = currentDeviceVersion;
  // if (currentDeviceVersion < 201 && !LeConfig.DEBUG_MODE) {
  // LeConfig.isDeviceVersionMatch = false;
  // CustomOneBtnDialog.Builder cdb = new CustomOneBtnDialog.Builder(
  // getApplicationContext()).setTitle("升级提示")
  // .setMessage("请更新您的小小班设备")
  // .setPositiveButton("确定", new DialogInterface.OnClickListener() {
  //
  // @Override
  // public void onClick(DialogInterface dialog, int which) {
  // dialog.dismiss();
  // }
  // });
  // CustomOneBtnDialog cd = cdb.create();
  // cd.setCancelable(false);
  // cd.setCanceledOnTouchOutside(false);
  // cd.show();
  // } else {
  // LeConfig.isDeviceVersionMatch = true;
  // }
  // } catch (NumberFormatException nfe) {
  // return;
  // }
  // }
  // }

  private void getBabyAvatar(String remoteBabyAvatar) {

    if (Tools.isEmpty(remoteBabyAvatar)
        || remoteBabyAvatar.equalsIgnoreCase("null")) {
      return;
    }

    SharedPreferences prefs = this.getSharedPreferences(Constant.USER_INFO,
        Context.MODE_PRIVATE);

    String babyImagePath = prefs.getString(Constant.BABY_AVATAR, "");
    // if (babyImagePath.equals("")) {

    new AsyncTask<String, Void, Bitmap>() {
      @Override
      protected void onPostExecute(Bitmap result) {
        if (result != null) {
          String path = PathUtil.getBabyAvatarPath(getApplicationContext());
          FileOutputStream out = null;
          File babyAvatarFile = new File(path);
          try {
            out = new FileOutputStream(babyAvatarFile);
            result.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is
                                                                  // your
                                                                  // Bitmap
                                                                  // instance
            // PNG is a lossless format, the compression factor (100) is
            // ignored
            SharedPreferences prefs = getSharedPreferences(Constant.USER_INFO,
                Context.MODE_PRIVATE);
            Uri babyAvatarUri = Uri.fromFile(babyAvatarFile);
            prefs.edit()
                .putString(Constant.BABY_AVATAR, babyAvatarUri.toString())
                .apply();
          } catch (Exception e) {
            e.printStackTrace();
          } finally {
            try {
              if (out != null) {
                out.close();
              }
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
        }
      }

      @Override
      protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];

        Bitmap resultImage = null;

        URL url;
        try {
          url = new URL(urldisplay);

          HttpURLConnection urlConnection = (HttpURLConnection) url
              .openConnection();

          urlConnection.setRequestMethod("GET");
          // urlConnection.setDoOutput(true);

          urlConnection.connect();

          InputStream in = urlConnection.getInputStream();

          // InputStream in = new java.net.URL(urldisplay).openStream();
          resultImage = BitmapFactory.decodeStream(in);

        } catch (MalformedURLException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
        return resultImage;
      }
    }.execute(remoteBabyAvatar);

    // }
  }

  private void register() {
    startActivity(new Intent(this, RegisterActivity.class));
    overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
  }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {
    case R.id.login:
       login();
      break;
    case R.id.tv_register:
      register();
      break;
    case R.id.find_password:
      startActivity(new Intent(this, GetLostPasswordActivity.class));
      overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
      break;
    default:
      break;
    }
  }
}
